import docker
import subprocess


class Container:
    """
    容器内操作docker
    """
    ContainerIDCommand = r'cat /proc/self/cgroup | grep "docker\|kubepods" | head -n 1'

    def __init__(self, socks=None):
        self.cli = None
        self.init(socks=socks)

    def init(self, socks):
        if not socks:
            self.cli = docker.from_env()
        else:
            self.cli = docker.DockerClient(socks)

    def get_container_id(self):
        """获取容器ID"""
        resp = subprocess.run(['/bin/sh', '-c', self.ContainerIDCommand], capture_output=True, text=True)
        container_id = resp.stdout.strip().split('/')[-1]
        return container_id

    def get_default_mac(self, image_name):
        """获取默认mac地址"""
        image = self.cli.images.get(image_name)  # 该镜像内需要包含command能执行的命令
        c = self.cli.containers.create(image,
                                       command=[
                                         '/bin/sh',
                                         '-c',
                                         """IF=${IF:-$(ip route show default|awk '/default/ {print $5}'|head -1)}
                                         cat /sys/class/net/$IF/address"""],
                                       network_mode='host')
        c.start()  # 启动容器
        mac = c.logs().decode().strip().split('\n')[-1]  # 执行容器内查询命令
        c.remove(v=True, force=True)
        return mac


if __name__ == '__main__':
    container = Container()
    mac = container.get_default_mac('nginx:latest')
    print(mac)
